<?php
namespace tp5_lib\notify\extension;

use tp5_lib\install\logic\DynamicConfig;

/**
 * 第三方服务器回调控制器的基类
 * 因为这种调用无法查看结果，所以将结果保留到日志中
 * 必须返回第三方指定的内容
 */
class NotifyBaseController
{
    protected $name="base";//记录文件名
    protected $message="";//需要写到记录中的信息
    protected $error=[];//收集到的错误
    protected $failed="failed";//处理失败时返回的信息
    public function __construct()
    {
        ob_start();
        register_shutdown_function([$this,"onShutdown"]);
        set_error_handler([$this,"onError"]);
        set_exception_handler([$this,"onException"]);
    }
    public function onShutdown()
    {
        $record=[
            "post"=>$_POST,
            "message"=>$this->message,
            "error"=>$this->error,
            "output"=>ob_get_contents(),
        ];
        $cwd=getcwd();
        chdir(__DIR__."/../../../public");
        DynamicConfig::alloc("record")->write($this->name."-".time(),$record);
        chdir($cwd);
    }
    public function onError($errno, $errstr , $errfile, $errline)
    {
        $this->error=[
            "type"=>"error",
            "message"=>$errstr,
            "code"=>$errno,
            "file"=>$errfile,
            "line"=>$errline,
        ];
        echo $this->failed;
        exit;
    }
    public function onException($ex)
    {
        $this->error=[
            "type"=>"exception",
            "message"=>$ex->getMessage(),
            "code"=>$ex->getCode(),
            "file"=>$ex->getFile(),
            "line"=>$ex->getLine(),
            "trace"=>$ex->getTrace(),
        ];
        echo $this->failed;
        exit;
    }
    public function error($message)
    {
        $this->message=$message;
        echo $this->failed;
        exit;
    }
}
